package TrafficSim;

public class Worker extends Thread {

	private VehicleLists vehicleLists; // Zeiger auf Autoliste (Datenpool)

	public Worker(VehicleLists vehicleLists) {
		// System.out.println("Worker erstellt");
		this.vehicleLists = vehicleLists;
		new Thread(this).start();
	}

	public synchronized void run() {

		while (true) {

			try {
				// System.out.println("Worker wartet");
				wait(); // wartet auf Master

			} catch (InterruptedException e) {

				e.printStackTrace();
			}

			while (true) {
				if (vehicleLists.isEmpty()) {
					break;
				}
				// fertiges Auto in

				Vehicle vehicle = vehicleLists.getTask();
				if (vehicle == null) {
					break;// Arbeit holen
				}
				// System.out.println("Arbeit geholt");
				boolean finish = vehicle.update(); // Auto berechnen
				if (finish) {
					vehicleLists.insertInCloneList(vehicle);
				} else {
					
					this.vehicleLists.destroyVehicle();
//					System.out.println("Vehicle destroyed");
//					System.out.println(vehicleLists.isEmpty());
				}
				// einfuegen
			}
		}
	}
}
